package com.alibaba.citrus.cr.b2b.trade.order.repository.impl;

import com.alibaba.citrus.cr.b2b.trade.order.facade.common.SetOrderTag;
import com.alibaba.citrus.cr.b2b.trade.order.repository.OrderQueryServiceRepository;
import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.constant.SaleOrderConstants;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.common.exception.RepositoryException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.common.util.PageUtils;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.esdegrade.service.EsDegradeService;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.platform_enhance.SaleOrderTag;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crb2btradecenter.domain.order.dto.LoadOrderListRequest;
import com.epoch.app.crb2btradecenter.domain.order.dto.LoadOrderRequest;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOrderBizIdsRequest;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOuterOrderIdsRequest;
import com.epoch.app.crb2btradecenter.domain.order.model.Order;
import com.epoch.app.crb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.LoadListResponse;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.OrderLineLoadListRequest;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.QueryOrderLineByMainIdListRequest;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.crb2btradecenter.dto.OrderDetailDTO;
import com.epoch.app.crb2btradecenter.dto.request.OrderPageQueryRequest;
import com.epoch.app.crb2btradecenter.dto.request.OrderQueryRequest;
import com.epoch.app.crb2btradecenter.dto.response.OrderPageQueryResponse;
import com.epoch.app.crb2btradecenter.dto.response.OrderQueryResponse;
import com.epoch.app.crb2btradecenter.enums.OrderStatus;
import com.epoch.app.crb2btradecenter.model.dto.PageQueryOrderEsListRequest;
import com.epoch.app.crb2btradecenter.model.dto.SelectCombox;
import com.epoch.app.crb2btradecenter.obtcsaleorderindex.model.ObtcSaleOrderIndex;
import com.epoch.app.crb2btradecenter.obtcsaleorderindex.service.ObtcSaleOrderIndexService;
import com.epoch.app.crb2btradecenter.sdo.DeliverOrderSDO;
import com.epoch.app.crb2btradecenter.sdo.DeliveryOrderDetailSDO;
import com.epoch.app.crb2btradecenter.sdo.OrderSDO;
import com.epoch.app.crforecastsales.domian.forecastorder.dto.LoadForecastOrderRequest;
import com.epoch.app.crforecastsales.domian.forecastorder.model.ForecastOrder;
import com.epoch.app.crforecastsales.domian.forecastorder.service.ForecastOrderService;
import com.epoch.app.crforecastsales.model.dto.ActivitySDO;
import com.epoch.app.crplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.CustomerAddressLoadListRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.model.dto.QueryDictionaryRequest;
import com.epoch.app.crplatformenhance.sdo.DictionarySDO;
import com.epoch.app.crunifiedinventory.consignmentorder.model.ConsignmentOrder;
import com.epoch.app.crunifiedinventory.consignmentorder.service.ConsignmentOrderService;
import com.epoch.app.crunifiedinventory.consignmentorderline.dto.BatchQueryRequest;
import com.epoch.app.crunifiedinventory.consignmentorderline.model.ConsignmentOrderLine;
import com.epoch.app.crunifiedinventory.consignmentorderline.service.ConsignmentOrderLineService;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderLoadListRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Component
public class OrderQueryServiceRepositoryImpl implements OrderQueryServiceRepository {
    private Log log = Log.getLogger(OrderQueryServiceRepositoryImpl.class);

    //单据原因
    private static final String ORDER_REASON_TYPE = "orderReason";
    //交货单，feature key
    private static final String DELIVERY_NO = "deliveryOrderLineNo";
    //调拨单业务ID
    private static final String ALLOCATE_ORDER_BIZ_ID = "allocateOrderBizId";
    //调拨单业务ID
    private static final String ALLOCATE_ORDER_ID = "allocateOrderId";
    //运输方式
    private static final String SHIP_METHOD_TYPE = "shipMethod";
    //时间格式
    private static final String STAN_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    //换货单标签
    private static final String EXCHANGE_ORDER_TAG = "exchange";

    @Resource
    private OrderService orderService;
    @Resource
    private ObtcSaleOrderIndexService obtcSaleOrderIndexService;
    @Resource
    private DictionaryQueryService dictionaryQueryService;
    @Resource
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    private OrderLineService orderLineService;
    @Autowired(required = false)
    private BaseDataService baseDataService;
    @Resource
    private ConsignmentOrderService consignmentOrderService;
    @Resource
    private ConsignmentOrderLineService consignmentOrderLineService;
    @Resource
    private EsDegradeService esDegradeService;
    @Resource
    private ForecastOrderService forecastOrderService;
    @Resource
    private CustomerAddressService customerAddressService;

    @Override
    @RepositoryInvoker
    public PageResult<List<OrderPageQueryResponse>> pageQuery(OrderPageQueryRequest request) {
        LoadOrderListRequest loadOrderListRequest = queryRequestConverter(request);
        Result<List<Order>> listResult = orderService.loadOrderList(loadOrderListRequest);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new PageResult<>(new ArrayList<>(), 0);
        }
        List<Order> orderList = listResult.getResult();
        List<OrderPageQueryResponse> orderPageQueryResponses = orderList.stream().map(order -> {
            OrderPageQueryResponse orderPageQueryResponse = new OrderPageQueryResponse();
            if (null != order.getId()) {
                orderPageQueryResponse.setId(String.valueOf(order.getId()));
            }
            if (!StringUtils.isEmpty(order.getOrderType())) {
                String desc = Arrays.stream(SaleOrderTag.values()).filter(x -> order.getOrderType().equals(x.getCode()))
                        .map(SaleOrderTag::getDesc).findFirst().orElse(null);
                orderPageQueryResponse.setOrderType(desc);
            }
            if (StringUtils.isNotBlank(order.getFeatures())) {
                Map<String, String> features = JSONObject.parseObject(order.getFeatures(), Map.class);
                orderPageQueryResponse.setMessageDesc(features.get(SaleOrderConstants.EXT_MESSAGE));
            }
            orderPageQueryResponse.setRelationNo(order.getRelationNo());
            orderPageQueryResponse.setOrderCategoryCode(order.getOrderCategoryCode());
            orderPageQueryResponse.setOuterId(order.getOuterOrderId());
            orderPageQueryResponse.setOrderTag(order.getOrderTag());
            orderPageQueryResponse.setOrderBizId(order.getOrderBizId());
            orderPageQueryResponse.setCustomerName(order.getCustomerName());
            orderPageQueryResponse.setSalesOrganization(order.getOrganizationName());
            orderPageQueryResponse.setBuzChannel(order.getChannelName());
            orderPageQueryResponse.setGoodsGroup(order.getProductGroupName());
            orderPageQueryResponse.setSaleChannel(order.getSaleChannelName());
            orderPageQueryResponse.setSaleDepartment(order.getDepartmentName());
            orderPageQueryResponse.setCreator(order.getCreatorName());
            orderPageQueryResponse.setRemark(order.getRemark());
            orderPageQueryResponse.setReceiveAddressCode(order.getReceiveAddressCode());
            orderPageQueryResponse.setReceiveDetailAddressName(order.getReceiveDetailAddress());
            orderPageQueryResponse.setWareHouseCode(order.getWareHouseCode());
            //2023.02.28 收货仓库
            orderPageQueryResponse.setReceiveWareHouseCode(order.getReceiveWareHouseCode());
            orderPageQueryResponse.setFrontOrderId(order.getFrontOrderId());
            if (order.getStatus() != null) {
                orderPageQueryResponse.setStatusCode(String.valueOf(order.getStatus()));
                String desc = Arrays.stream(OrderStatus.values()).filter(s -> order.getStatus().equals(s.getCode()))
                        .map(OrderStatus::getDesc).findFirst().orElse(null);
                orderPageQueryResponse.setStatus(desc);
            }
            if (null != order.getGmtCreate()) {
                SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
                String format = spf.format(order.getGmtCreate());
                orderPageQueryResponse.setOrderTime(format);
            }

            //add by 皓晖 at 20211216 for 新增加版本号 begin
            orderPageQueryResponse.setSyncVersion(order.getSyncVersion());
            //add by 皓晖 at 20211216 for 新增加版本号 end

            return orderPageQueryResponse;
        }).collect(Collectors.toList());
        return PageResult.of(orderPageQueryResponses, listResult.getTotal());
    }

    @Override
    @RepositoryInvoker
    public OrderQueryResponse query(OrderQueryRequest request) {
        if (StringUtil.isNotEmpty(request.getId())) {
            LoadOrderRequest loadOrderRequest = LoadOrderRequest.builder().build();
            loadOrderRequest.setId(request.getId());
            Order order = orderService.loadOrder(loadOrderRequest);
            if (Objects.isNull(order)) {
                throw new RepositoryException("OTS-05-001-10-16-004");
            }
            OrderQueryResponse orderQueryResponse = orderQueryResponseConverter(order);
            //获取预报订单业务单号
            if (StringUtils.isNotBlank(order.getFrontOrderId())) {
                //替换掉查ES
                LoadForecastOrderRequest loadForecastOrderRequest = new LoadForecastOrderRequest();
                loadForecastOrderRequest.setId(order.getFrontOrderId());
                ForecastOrder forecastOrder = forecastOrderService.loadForecastOrder(loadForecastOrderRequest);
                if (Objects.nonNull(forecastOrder)){
                    orderQueryResponse.setFrontOrderBizId(forecastOrder.getOrderBizId());
                }
            }

            JSONObject features = null;
            if (StringUtils.isNotBlank(order.getFeatures())) {
                features = JSONObject.parseObject(order.getFeatures());
                orderQueryResponse.setAllocateOrderId(features.getString(ALLOCATE_ORDER_ID));
                orderQueryResponse.setAllocateOrderBizId(features.getString(ALLOCATE_ORDER_BIZ_ID));
            }

            QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
            //获取单据原因的名称
            if (StringUtils.isNotBlank(order.getCreateReason())) {
                queryDictionaryRequest.setDictCode(ORDER_REASON_TYPE);
                Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
                dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                    if (x.getValueData().equals(order.getCreateReason())) {
                        orderQueryResponse.setOrderReasonName(x.getValueName());
                    }
                });
            }

            //获取配送方式名称
            if (StringUtils.isNotBlank(order.getTransportModeCode())) {
                queryDictionaryRequest.setDictCode(SHIP_METHOD_TYPE);
                Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
                dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                    if (x.getValueData().equals(order.getTransportModeCode())) {
                        orderQueryResponse.setDeliveryMethodName(x.getValueName());
                    }
                });
            }

            //获取收货地址
            if (StringUtils.isNotBlank(order.getReceiveAddressCode())) {
                if (Objects.nonNull(features) && "OrderCenter".equals(features.get("os"))) {
                    // todo 走新客户中心查询数据
                    orderQueryResponse.setAddressName(order.getReceiveDetailAddress());
                    orderQueryResponse.setSalesmanName(order.getSalesmanName());
                    log.info("OrderQueryServiceRepositoryImpl#query order={}", order);
                } else {
                    //查询数据库
                    CustomerAddressLoadListRequest customerAddressLoadListRequest = new CustomerAddressLoadListRequest();
                    customerAddressLoadListRequest.setAddressCode(order.getReceiveAddressCode());
                    customerAddressLoadListRequest.setCustomerCode(order.getCustomerCode());
                    customerAddressLoadListRequest.setOrgSaleOrganizationCode(order.getOrganizationCode());
                    customerAddressLoadListRequest.setChannelCode(order.getChannelCode());
                    customerAddressLoadListRequest.setItemGroup(order.getProductGroupCode());
                    Result<List<CustomerAddress>> customerAddressList = customerAddressService.loadCustomerAddressList(customerAddressLoadListRequest);
                    if (Objects.isNull(customerAddressList) || CollectionUtils.isEmpty(customerAddressList.getResult())){
                        throw new FunctionException("OTS-05-001-10-16-014", "未查询到客户收货地址数据");
                    }
                    CustomerAddress customerAddress = customerAddressList.getResult().get(0);
                    if (StringUtils.isBlank(customerAddress.getOrgSaleOrganizationCode())){
                        throw new FunctionException("OTS-05-001-10-16-015", "未查询到客户组织编码");
                    }
                    orderQueryResponse.setAddressName(customerAddress.getAddressName());
                    if (StringUtils.isNotBlank(customerAddress.getPrincipal())){
                        //根据员工id查询员工名称
                        BaselineGetEmployeeByIdsRequest baselineGetEmployeeByIdsRequest = new BaselineGetEmployeeByIdsRequest();
                        baselineGetEmployeeByIdsRequest.setEmployeeIdList(Lists.newArrayList(customerAddress.getPrincipal()));
                        Result<List<EmployeeSDO>> employeeResult = baseDataService.baselineGetEmployeeByIds(baselineGetEmployeeByIdsRequest);
                        if (employeeResult != null && CollectionUtils.isNotEmpty(employeeResult.getResult())){
                            orderQueryResponse.setSalesmanName(employeeResult.getResult().get(0).getName());
                        }
                    }
                }
            }

            //获取发货仓库
            if (StringUtils.isNotBlank(order.getWareHouseName())) {
                orderQueryResponse.setShippingWarehouseName(order.getWareHouseName());
            } else {
                if (null != order.getWareHouseCode()) {
                    QueryWarehouseByIdRequest queryCargoZoneByIdRequest = new QueryWarehouseByIdRequest();
                    queryCargoZoneByIdRequest.setId(order.getWareHouseCode());


                    Result<WarehouseInfo> warehouseInfoResult = unifiedInventoryService.queryWarehouseById(queryCargoZoneByIdRequest);
                    if (warehouseInfoResult != null && warehouseInfoResult.getResult() != null) {
                        orderQueryResponse.setShippingWarehouseName(warehouseInfoResult.getResult().getName());
                    } else {
                        //理论上warehouseCode这里指代逻辑仓库id,不应该执行下面这段逻辑
                        SearchCargoZoneListByDBRequest searchCargoZoneListByDBRequest = new SearchCargoZoneListByDBRequest();
                        searchCargoZoneListByDBRequest.setWarehouseCode(order.getWareHouseCode());
                        SearchCargoZoneListByDBResponse response = unifiedInventoryService.searchCargoZoneListByDB(searchCargoZoneListByDBRequest);
                        if (Objects.nonNull(response) && CollectionUtils.isNotEmpty(response.getResult())){
                            orderQueryResponse.setShippingWarehouseName(response.getResult().get(0).getName());
                        }
                    }
                }
            }
            //2023.02.27 获取收货仓库
            if (SaleOrderTag.EXCHANGE_ORDER.getCode().equals(order.getOrderType())){
                if (StringUtils.isNotBlank(order.getReceiveWareHouseCode())){
                    QueryWarehouseByIdRequest queryCargoZoneByIdRequest = new QueryWarehouseByIdRequest();
                    queryCargoZoneByIdRequest.setId(order.getReceiveWareHouseCode());
                    Result<WarehouseInfo> warehouseInfoResult = unifiedInventoryService.queryWarehouseById(queryCargoZoneByIdRequest);
                    if (warehouseInfoResult != null && warehouseInfoResult.getResult() != null) {
                        orderQueryResponse.setReceiveWareHouseName(warehouseInfoResult.getResult().getName());
                    }
                }
            }

            OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
            orderLineLoadListRequest.setMainOrderId(request.getId());
            orderLineLoadListRequest.setStart(0);
            orderLineLoadListRequest.setLimit(999);
            LoadListResponse loadListResponse = orderLineService.loadList(orderLineLoadListRequest);
            log.info("OrderQueryServiceRepositoryImpl#query loadListResponse:{}", JSONObject.toJSONString(loadListResponse));
            AtomicLong orderTotalFee= new AtomicLong(0L);
            if (loadListResponse.getResult() != null) {
                List<OrderLine> result = loadListResponse.getResult();
                List<OrderDetailDTO> orderDetailDTOList = result.stream().map(orderLine -> {
                    OrderDetailDTO orderDetailDTO = OrderDetailDTOConverter(orderLine);
                    //将库存单位转换为一个销售单位list，用于页面展示

                    if (orderLine.getSaleUnit() != null && orderLine.getSaleUnitName() != null
                            && orderLine.getUnitConvert() != null) {
                        List<SelectCombox> saleUnitList = new ArrayList<>();
                        SelectCombox selectCombox = new SelectCombox();
                        selectCombox.setLabel(orderLine.getSaleUnitName());
                        selectCombox.setValue(orderLine.getSaleUnit());
                        selectCombox.setExt(orderLine.getUnitConvert());
                        saleUnitList.add(selectCombox);
                        orderDetailDTO.setSaleUnitList(saleUnitList);
                    }
                    if (StringUtils.isNotBlank(orderLine.getFeatures())) {
                        HashMap<String, String> hashMap = JSONObject.parseObject(orderLine.getFeatures(), HashMap.class);
                        if (!MapUtils.isEmpty(hashMap) && Objects.nonNull(hashMap.get(DELIVERY_NO))) {
                            orderDetailDTO.setDeliveryNo(null == hashMap.get(DELIVERY_NO) ? "" : String.valueOf(hashMap.get(DELIVERY_NO)));
                        }
                        if (!MapUtils.isEmpty(hashMap)) {
                            //手工价格
                            orderDetailDTO.setManualPrice(StringUtils.isNotBlank(hashMap.get(SaleOrderConstants.MANUAL_PRICE)) ? hashMap.get(SaleOrderConstants.MANUAL_PRICE) : null);
                            //手工总金额
                            orderDetailDTO.setManualTotalAmount(StringUtils.isNotBlank(hashMap.get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT)) ? hashMap.get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT) : null);
                        }
                    }
                    if (StringUtils.isNotBlank(orderDetailDTO.getManualTotalAmount())) {
                        orderTotalFee.addAndGet(Long.parseLong(orderDetailDTO.getManualTotalAmount()));
                    }

                    return orderDetailDTO;
                }).collect(Collectors.toList());
                orderQueryResponse.setOrderDetailList(orderDetailDTOList);
                orderQueryResponse.setOrderTotalFee(orderTotalFee.get());
            }

            DeliverOrderSDO deliverOrderSDO = new DeliverOrderSDO();
            if (order.getId() != null) {
                deliverOrderSDO.setOrderId(order.getId().toString());
            }
            deliverOrderSDO.setDetailAddress(order.getReceiveDetailAddress());
            deliverOrderSDO.setCustomerCode(order.getCustomerCode());
            deliverOrderSDO.setDeliveryPartCode(order.getDepartmentCode());
            deliverOrderSDO.setDeliveryPartName(order.getDepartmentName());
            deliverOrderSDO.setWarehouseCode(order.getWareHouseCode());
            deliverOrderSDO.setWarehouseName(order.getWareHouseName());
            deliverOrderSDO.setDeliveryTime(order.getCustomerExpectDate());
            deliverOrderSDO.setReceiveTime(order.getEndTime());
            deliverOrderSDO.setDeliveryStatus(order.getDeliveryStatus());
            deliverOrderSDO.setTransportModeCode(order.getTransportModeCode());
            deliverOrderSDO.setTransportModeName(order.getTransportModeName());
            deliverOrderSDO.setCreator(order.getCreatorName());
            deliverOrderSDO.setUpdater(order.getModifier());
            deliverOrderSDO.setContact(order.getContact());
            deliverOrderSDO.setContactPhone(order.getContactPhone());
            //子单
            List<DeliveryOrderDetailSDO> collect = orderQueryResponse.getOrderDetailList().stream().map(orderDetailDTO -> {
                DeliveryOrderDetailSDO detailSDO = new DeliveryOrderDetailSDO();
                detailSDO.setCustomerCode(order.getCustomerCode());
                detailSDO.setDeliveryTime(order.getCustomerExpectDate());
                detailSDO.setReceiveTime(order.getEndTime());
                detailSDO.setDeliveryStatus(order.getDeliveryStatus());
                detailSDO.setCreator(order.getCreatorName());
                detailSDO.setUpdater(order.getModifier());
                return detailSDO;
            }).collect(Collectors.toList());
            deliverOrderSDO.setDeliveryOrderDetailSDOS(collect);
            orderQueryResponse.setDeliverOrderSDO(deliverOrderSDO);
            orderQueryResponse.setFulfillmentPriority(order.getFulfillmentPriority());
            orderQueryResponse.setFulfillmentTypeCode(order.getFulfillmentTypeCode());
            orderQueryResponse.setAutoFulfillment(order.getAutoFulfillment());
            return orderQueryResponse;
        }
        return new OrderQueryResponse();
    }

    @Override
    @RepositoryInvoker
    public OrderSDO querySingle(OrderQueryRequest request) {
        LoadOrderRequest loadOrderRequest = LoadOrderRequest.builder().build();
        loadOrderRequest.setId(request.getId());
        Order order = orderService.loadOrder(loadOrderRequest);


        OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
        orderLineLoadListRequest.setMainOrderId(request.getId());
        orderLineLoadListRequest.setStart(0);
        orderLineLoadListRequest.setLimit(999);
        OrderSDO orderSDO = new OrderSDO();
        LoadListResponse loadListResponse = orderLineService.loadList(orderLineLoadListRequest);
        if (loadListResponse != null) {
            List<OrderLine> result = loadListResponse.getResult();
            List<OrderLine> orderLineList = toList(result, OrderLine.class);
            orderSDO = OrderConvert.convertToOrderSDO(order, orderLineList);
        }

        return orderSDO;
    }

    @Override
    public List<OrderSDO> queryByOrderBizIds(QueryByOrderBizIdsRequest request, boolean needLines) {
        try {
            if (CollectionUtils.isEmpty(request.getOrderBizIds()) && CollectionUtils.isEmpty(request.getPreOrderNoList())) {
                return Lists.newArrayList();
            }
            if (Objects.isNull(request.getLimit())) {
                request.setLimit(request.getOrderBizIds().size());
            }
            Result<List<Order>> ordersResult = orderService.queryByOrderBizIds(request);
            if (!ordersResult.isSuccess() || CollectionUtils.isEmpty(ordersResult.getResult())) {
                return Lists.newArrayList();
            }
            List<Order> orders = ordersResult.getResult();
            if (!needLines) {
                return orders.stream().map(p -> OrderConvert.convertToOrderSDO(p, null)).collect(Collectors.toList());
            }

            List<OrderSDO> orderSDOList = Lists.newArrayList();
            for (Order order : orders) {
                OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
                orderLineLoadListRequest.setMainOrderId(order.getId().toString());
                orderLineLoadListRequest.setStart(0);
                orderLineLoadListRequest.setLimit(999);
                OrderSDO orderSDO = new OrderSDO();
                LoadListResponse loadListResponse = orderLineService.loadList(orderLineLoadListRequest);
                if (loadListResponse != null) {
                    List<OrderLine> result = loadListResponse.getResult();
                    List<OrderLine> orderLineList = toList(result, OrderLine.class);
                    orderSDO = OrderConvert.convertToOrderSDO(order, orderLineList);
                }
                orderSDOList.add(orderSDO);
            }
            return orderSDOList;
        } catch (Exception e) {
            log.error("OrderQueryServiceRepositoryImpl#queryByOrderBizIds error", e);
        }
        return Lists.newArrayList();
    }

    @Override
    @RepositoryInvoker
    public OrderSDO queryByOuterOrderId(String outerOrderId) {
        QueryByOuterOrderIdsRequest request = QueryByOuterOrderIdsRequest.builder()
                .outerOrderIds(Lists.newArrayList(outerOrderId)).build();
        Result<List<Order>> orderResult = orderService.queryByOuterOrderIds(request);
        if (!orderResult.isSuccess() || CollectionUtils.isEmpty(orderResult.getResult())) {
            return null;
        }
        Order order = orderResult.getResult().get(0);

        OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
        orderLineLoadListRequest.setMainOrderId(order.getId().toString());
        orderLineLoadListRequest.setStart(0);
        orderLineLoadListRequest.setLimit(999);
        OrderSDO orderSDO = new OrderSDO();
        LoadListResponse loadListResponse = orderLineService.loadList(orderLineLoadListRequest);
        if (loadListResponse != null) {
            List<OrderLine> result = loadListResponse.getResult();
            List<OrderLine> orderLineList = toList(result, OrderLine.class);
            orderSDO = OrderConvert.convertToOrderSDO(order, orderLineList);
        }
        return orderSDO;
    }

    private static <T> List<T> toList(List list, Class<T> clazz) {
        return JSONArray.parseArray(JSONObject.toJSONString(list), clazz);
    }

    private OrderQueryResponse orderQueryResponseConverter(Order order) {
        OrderQueryResponse orderQueryResponse = new OrderQueryResponse();
        if (null != order.getId()) {
            orderQueryResponse.setId(String.valueOf(order.getId()));
        }
        orderQueryResponse.setFrontOrderId(order.getFrontOrderId());
        if (null != order.getStatus()) {
            orderQueryResponse.setOrderStatus(String.valueOf(order.getStatus()));
        }
        orderQueryResponse.setOrderBizId(order.getOrderBizId());
        orderQueryResponse.setAreaCode(order.getAreaCode());
        orderQueryResponse.setBisUnitCode(order.getBisUnitCode());
        orderQueryResponse.setSalesmanCode(order.getSalesmanId());
        orderQueryResponse.setUpdator(order.getModifierName());

        orderQueryResponse.setAddressCode(order.getReceiveAddressCode());
        orderQueryResponse.setReceiveAddressName(order.getReceiveDetailAddress());
        orderQueryResponse.setDeliveryAddr(order.getReceiveAddressCode());
        orderQueryResponse.setCustomerName(order.getCustomerName());
        orderQueryResponse.setCustomerCode(order.getCustomerCode());
        orderQueryResponse.setShippingWarehouse(order.getWareHouseCode());
        orderQueryResponse.setShippingWarehouseCode(order.getWareHouseOutCode());
        //2023.02.27收货仓库
        orderQueryResponse.setReceiveWareHouseCode(order.getReceiveWareHouseCode());
        orderQueryResponse.setReceiveWareHouseName(order.getReceiveWareHouseName());
        orderQueryResponse.setSalesOrganization(order.getOrganizationCode());
        orderQueryResponse.setBuzChannel(order.getChannelCode());
        orderQueryResponse.setSaleChannel(order.getSaleChannelCode());
        orderQueryResponse.setSaleDepartment(order.getDepartmentCode());
        orderQueryResponse.setOrderTag(order.getOrderTag());
        orderQueryResponse.setCustomerAccounts(order.getCustomerAccounts());
        orderQueryResponse.setCostCenter(order.getCostCenter());
        orderQueryResponse.setCashCustomerName(order.getCashCustomerName());
        orderQueryResponse.setCustomerRefNo(order.getCustomerReferenceNo());
        orderQueryResponse.setRemark(order.getRemark());
        orderQueryResponse.setGoodsGroup(order.getProductGroupCode());
        orderQueryResponse.setGoodsGroupName(order.getProductGroupName());
        orderQueryResponse.setOuterId(order.getOuterOrderId());
        if (null != order.getGmtModified()) {
            SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
            orderQueryResponse.setUpdateTime(spf.format(order.getGmtModified()));
        }
        orderQueryResponse.setOrderReason(order.getCreateReason());
        orderQueryResponse.setFeatures(order.getFeatures());
        orderQueryResponse.setBizFeatures(order.getBizFeatures());
        orderQueryResponse.setCreator(order.getCreatorName());
        String creator = order.getCreator();
        if (StringUtils.isNotBlank(creator)){
            JSONObject jsonObject = JSONObject.parseObject(creator);
            String empId = jsonObject.getString("empId");
            if (StringUtils.isNotBlank(empId)&&empId.startsWith("CZ_")){
                //截取CZ_前缀
                String bigIntEmpId = empId.substring(3);
                orderQueryResponse.setCreatorId(bigIntEmpId);
            }
        }

        if (null != order.getCustomerExpectDate()) {
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
            orderQueryResponse.setCustomerRefDate(spf.format(order.getCustomerExpectDate()));
        }
        orderQueryResponse.setContact(order.getContact());
        orderQueryResponse.setContactPhone(order.getContactPhone());
        orderQueryResponse.setDeliveryMethod(order.getTransportModeCode());
        orderQueryResponse.setOrderType(order.getOrderType());
        if (null != order.getGmtCreate()) {
            SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
            orderQueryResponse.setOrderTime(spf.format(order.getGmtCreate()));
        }
        if (null != order.getOrderType()) {
            SaleOrderTag saleOrderTag = SaleOrderTag.of(order.getOrderType());
            if (Objects.nonNull(saleOrderTag)) {
                orderQueryResponse.setOrderTypeName(saleOrderTag.getDesc());
            }
        }
        if (null != order.getOrganizationName()) {
            orderQueryResponse.setSalesOrganizationName(order.getOrganizationName());
        }
        orderQueryResponse.setBuzChannelName(order.getChannelName());
        orderQueryResponse.setSaleChannelName(order.getSaleChannelName());
        orderQueryResponse.setSaleDepartmentName(order.getDepartmentName());
        orderQueryResponse.setOrderReason(order.getCreateReason());
        orderQueryResponse.setDeliveryAddrName(order.getReceiveDetailAddress());
        orderQueryResponse.setShippingWarehouseName(order.getWareHouseName());
        orderQueryResponse.setDeliveryMethodName(order.getTransportModeName());
        orderQueryResponse.setSyncVersion(order.getSyncVersion());
        orderQueryResponse.setFromSys(order.getFromSys());
        orderQueryResponse.setBusinessType(order.getBusinessType());
        orderQueryResponse.setOrderCategoryCode(order.getOrderCategoryCode());
        return orderQueryResponse;
    }

    private OrderDetailDTO OrderDetailDTOConverter(OrderLine orderLine) {
        OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
        if (null != orderLine.getId()) {
            orderDetailDTO.setId(String.valueOf(orderLine.getId()));
        }
        orderDetailDTO.setOuterOrderLineId(orderLine.getOuterOrderLineId());
        orderDetailDTO.setGoodsCode(orderLine.getScItemOutCode());
        orderDetailDTO.setCategoryCode(orderLine.getCategoryCode());
        orderDetailDTO.setCategoryDesc(orderLine.getCategoryDesc());
        orderDetailDTO.setCategoryChildCode(orderLine.getCategoryChildCode());
        orderDetailDTO.setCategoryChildDesc(orderLine.getCategoryChildDesc());
        orderDetailDTO.setFirstCategoryCode(orderLine.getFirstCategoryCode());
        orderDetailDTO.setFirstCategoryDesc(orderLine.getFirstCategoryDesc());
        orderDetailDTO.setSecondCategoryCode(orderLine.getSecondCategoryCode());
        orderDetailDTO.setSecondCategoryDesc(orderLine.getSecondCategoryDesc());
        orderDetailDTO.setGoodsId(orderLine.getScItemId());
        orderDetailDTO.setGoodsName(orderLine.getScItemTitle());
        if (orderLine.getQuantity() != null) {
            orderDetailDTO.setQuantity(String.valueOf(orderLine.getQuantity()));
        }
        orderDetailDTO.setSaleUnit(orderLine.getSaleUnit());
        orderDetailDTO.setSaleUnitName(orderLine.getSaleUnitName());
        orderDetailDTO.setInventoryUnit(orderLine.getInventoryUnit());
        orderDetailDTO.setInventoryUnitCode(orderLine.getInventoryUnitCode());
        orderDetailDTO.setUnitConvert(orderLine.getUnitConvert());
        orderDetailDTO.setUnitPrice(orderLine.getUnitPrice());
        if (StringUtil.isNotEmpty(orderDetailDTO.getQuantity()) && StringUtil.isNotEmpty(orderDetailDTO.getUnitPrice())) {
            BigDecimal a = new BigDecimal(orderDetailDTO.getQuantity());
            BigDecimal b = new BigDecimal(orderDetailDTO.getUnitPrice());
            orderDetailDTO.setTotalAmount(String.valueOf(a.multiply(b)));
        }
        if (null != orderLine.getProductationTime()) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATETIME_FORMAT);
            String format = sdf.format(orderLine.getProductationTime());
            orderDetailDTO.setProducteDate(format);
        }
        orderDetailDTO.setRemark(orderLine.getRemark());
        orderDetailDTO.setLineNum(orderLine.getSerialNumber());
        orderDetailDTO.setSaleQuantity(orderLine.getQuantity());
        orderDetailDTO.setFeatures(orderLine.getFeatures());
        if (!StringUtils.isEmpty(orderLine.getActivityPrice())) {
//            Double activityPrice = Double.valueOf(orderLine.getActivityPrice());
            orderDetailDTO.setActivityUnitPrice(orderLine.getActivityPrice());
        }
        if (StringUtils.isNotEmpty(orderLine.getActualPaidFee())) {
            orderDetailDTO.setActivityTotalAmount(orderLine.getActualPaidFee());
        }
        if (!StringUtils.isEmpty(orderLine.getCumulativeReceiptQuantity())) {
            orderDetailDTO.setCumulativeShipmentQuantity(Integer.parseInt(orderLine.getCumulativeReceiptQuantity()));
        }
        orderDetailDTO.setActivityId(orderLine.getActivityCode());
        orderDetailDTO.setActivityDesc(orderLine.getActivityName());
        orderDetailDTO.setRejectReason(orderLine.getRefuseReasonCode());
        orderDetailDTO.setOrderLineTag(orderLine.getOrderLineTag());
        orderDetailDTO.setFrontOrderLineId(orderLine.getFrontOrderLineId());
        orderDetailDTO.setDeliveryAmount(orderLine.getDeliveryAmount());
        if (null != orderLine.getStatus()) {
            orderDetailDTO.setOrderStatus(String.valueOf(orderLine.getStatus()));
            orderDetailDTO.setOrderStatusName(OrderStatus.of(orderLine.getStatus()).getDesc());
        }

        //设置活动行号
        String activityNumber = null;
        if (StringUtils.isNotBlank(orderLine.getFeatures())) {
            Map<String, String> features = JSONObject.parseObject(orderLine.getFeatures(), Map.class);
            if (MapUtils.isNotEmpty(features)) {
                if ("gift".equals(features.get("giftFlag"))||StringUtils.isBlank(features.get("giftFlag"))) {
                    //设置赠品标识
                    orderDetailDTO.setIsGift(true);
                }

                List<ActivitySDO> activitySDOS = JSONObject.parseArray(features.get("activityDteails"), ActivitySDO.class);
                if (CollectionUtils.isNotEmpty(activitySDOS)) {
                    List<String> collect = activitySDOS.stream().map(ActivitySDO::getActivityTermid).collect(Collectors.toList());
                    activityNumber = collect.stream().collect(Collectors.joining("/"));
                }
            }
        }
        orderDetailDTO.setActivityLineNo(activityNumber);
        orderDetailDTO.setSyncVersion(orderLine.getSyncVersion());

        return orderDetailDTO;
    }

    private LoadOrderListRequest queryRequestConverter(OrderPageQueryRequest request) {
        LoadOrderListRequest loadOrderListRequest = new LoadOrderListRequest();
        if (!StringUtils.isEmpty(request.getId())) {
            loadOrderListRequest.setId(Long.parseLong(request.getId()));
        }
        loadOrderListRequest.setOrderTag(request.getOrderTag());
        loadOrderListRequest.setFrontOrderId(request.getFrontOrderId());
        loadOrderListRequest.setOuterOrderId(request.getOuterOrderId());
        loadOrderListRequest.setBizCode(request.getBizCode());
        loadOrderListRequest.setBusinessCode(request.getBusinessCode());
        loadOrderListRequest.setOrderType(request.getOrderType());
        loadOrderListRequest.setCustomerCode(request.getCustomerCode());
        loadOrderListRequest.setCustomerName(request.getCustomerName());
        loadOrderListRequest.setOrganizationCode(request.getOrganizationCode());
        loadOrderListRequest.setOrganizationName(request.getOrganizationName());
        if (!CollectionUtils.isEmpty(request.getDepartmentCodeList())) {
            loadOrderListRequest.setChannelList(request.getDepartmentCodeList());
        }
        loadOrderListRequest.setDepartmentName(request.getDepartmentName());
        if (!CollectionUtils.isEmpty(request.getProductGroupCodeList())) {
            loadOrderListRequest.setProductGroupCodeList(request.getProductGroupCodeList());
        }
        loadOrderListRequest.setProductGroupName(request.getProductGroupName());
        if (!CollectionUtils.isEmpty(request.getSaleChannelCodeList())) {
            loadOrderListRequest.setSaleChannelCodeList(request.getSaleChannelCodeList());
        }
        loadOrderListRequest.setSaleChannelName(request.getSaleChannelName());
        if (!CollectionUtils.isEmpty(request.getChannelCode())) {
            loadOrderListRequest.setChannelList(request.getChannelCode());
        }
        loadOrderListRequest.setChannelName(request.getChannelName());
        loadOrderListRequest.setReceiveAddressCode(request.getReceiveAddressCode());
        loadOrderListRequest.setReceiveDetailAddress(request.getReceiveDetailAddress());
        loadOrderListRequest.setStatus(request.getStatus());
        loadOrderListRequest.setOrderTotalFee(request.getOrderTotalFee());
        loadOrderListRequest.setActualPaidFee(request.getActualPaidFee());
        loadOrderListRequest.setShouldPayFee(request.getActualPaidFee());
        loadOrderListRequest.setPostFee(request.getPostFee());
        if (null != request.getPayStatus()) {
            loadOrderListRequest.setPayStatus(Integer.parseInt(request.getPayStatus()));
        }
        loadOrderListRequest.setPayTime(request.getPayTime());
        loadOrderListRequest.setDeliveryStatus(request.getDeliveryStatus());
        loadOrderListRequest.setEndTime(request.getEndTime());
        loadOrderListRequest.setTransportModeCode(request.getTransportModeCode());
        loadOrderListRequest.setTransportModeName(request.getTransportModeName());
        loadOrderListRequest.setWareHouseCode(request.getWareHouseCode());
        loadOrderListRequest.setWareHouseName(request.getWareHouseName());
        loadOrderListRequest.setCostCenter(request.getCostCenter());
        loadOrderListRequest.setCashCustomerName(request.getCashCustomerName());
        loadOrderListRequest.setSyncVersion(request.getSyncVersion());
        if (!CollectionUtils.isEmpty(request.getCreateReason())) {
            loadOrderListRequest.setCreateReasonList(request.getCreateReason());
        }
        loadOrderListRequest.setRemark(request.getRemark());
        loadOrderListRequest.setGmtCreate(request.getGmtCreate());
        loadOrderListRequest.setGmtModified(request.getGmtModified());
        loadOrderListRequest.setCreator(request.getCreator());
        loadOrderListRequest.setCreatorName(request.getCreatorName());
        loadOrderListRequest.setModifier(request.getModifier());
        loadOrderListRequest.setModifierName(request.getModifierName());
        loadOrderListRequest.setCustomerReferenceNo(request.getCustomerReferenceNo());
        loadOrderListRequest.setCustomerExpectDate(request.getCustomerExpectDate());
        loadOrderListRequest.setStart(request.getStart());
        loadOrderListRequest.setLimit(request.getLimit());
        loadOrderListRequest.setDir("gmtCreate");
        loadOrderListRequest.setAsc(false);
        return loadOrderListRequest;
    }

    @Override
    @RepositoryInvoker(errorCode = "OTS-05-001-10-16-001")
    public Result<List<OrderPageQueryResponse>> pageQueryES(PageQueryOrderEsListRequest request) {
        request.setDir("main_gmt_create");

        //单据创建日期
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(request.getOrderTime())) {
            request.setOrderStartTime(request.getOrderTime().get(0) == null ? null : DateUtils.string2Date(request.getOrderTime().get(0)));
            request.setOrderEndTime(request.getOrderTime().get(1) == null ? null : DateUtils.string2Date(request.getOrderTime().get(1)));
        }

        //单据修改日期
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(request.getUpdateTime())) {
            request.setUpdateStartTime(request.getUpdateTime().get(0) == null ? null : DateUtils.string2Date(request.getOrderTime().get(0)));
            request.setUpdateEndTime(request.getUpdateTime().get(1) == null ? null : DateUtils.string2Date(request.getOrderTime().get(1)));
        }
        Result<List<ObtcSaleOrderIndex>> listResult =new Result<>();
        if (esDegradeService.getEsDegradeValue()!=null&&esDegradeService.getEsDegradeValue().getResult()) {
            listResult= obtcSaleOrderIndexService.pageQueryOrderListByEsDegrade(request);
        }else{
           listResult = obtcSaleOrderIndexService.pageQueryOrderList(request);
        }
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new Result<>();
        }
        List<ObtcSaleOrderIndex> result = listResult.getResult();
        //2022.10.20 换货订单 需要区分是换货还是退货
        Map<String,Boolean> deliveryOrderMap = Maps.newHashMap();
        if (EXCHANGE_ORDER_TAG.equals(request.getOrderTag())){
            //交货单号 - true 换货  false 退货
            handleExchangeDeliveryOrder(deliveryOrderMap,listResult);
        }
        List<Long> mainIdList = result.stream().map(ObtcSaleOrderIndex::getMainId).collect(Collectors.toList());
        Map<Long, Long> saleOrderTotalFeeMap = new HashMap<>();
        if (SetOrderTag.RETURN.equals(request.getOrderTag())){
            saleOrderTotalFeeMap = getSaleOrderTotalFee(mainIdList);
        }
        Map<Long, Long> finalSaleOrderTotalFeeMap = saleOrderTotalFeeMap;
        List<OrderPageQueryResponse> orderPageQueryResponses = result.stream().map(obtcSaleOrderIndex -> {
            OrderPageQueryResponse orderPageQueryResponse = new OrderPageQueryResponse();
            if (null != obtcSaleOrderIndex.getMainId()) {
                orderPageQueryResponse.setId(String.valueOf(obtcSaleOrderIndex.getMainId()));
            }
            if (!StringUtils.isEmpty(obtcSaleOrderIndex.getMainOrderType())) {
//                String desc = Arrays.stream(SaleOrderTag.values()).filter(x -> obtcSaleOrderIndex.getMainOrderType().equals(x.getCode()))
//                        .map(SaleOrderTag::getDesc).findFirst().orElse(null);
                SaleOrderTag saleOrderTag = SaleOrderTag.of(obtcSaleOrderIndex.getMainOrderType());
                if (Objects.nonNull(saleOrderTag)) {
                    orderPageQueryResponse.setOrderType(saleOrderTag.getDesc());
                }
            }
            if (StringUtils.isNotBlank(obtcSaleOrderIndex.getMainFeatures())) {
                Map<String, String> features = JSONObject.parseObject(obtcSaleOrderIndex.getMainFeatures(), Map.class);
                orderPageQueryResponse.setMessageDesc(StringUtils.isNotBlank(features.get(SaleOrderConstants.EXT_MESSAGE)) ? features.get(SaleOrderConstants.EXT_MESSAGE) : null);
                orderPageQueryResponse.setFrontOrderBizId(StringUtils.isNotBlank(features.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID)) ? features.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID) : null);
                orderPageQueryResponse.setDeliveryOrderId(StringUtils.isNotBlank(features.get(SaleOrderConstants.DELIVERY_ORDER_ID)) ? features.get(SaleOrderConstants.DELIVERY_ORDER_ID) : null);
                orderPageQueryResponse.setCreditCheckStatus(features.get(SaleOrderConstants.CREDIT_CHECK_STATUS_NAME));
            }
            orderPageQueryResponse.setOrderBizId(obtcSaleOrderIndex.getMainOrderBizId());
            orderPageQueryResponse.setOuterId(obtcSaleOrderIndex.getMainOuterOrderId());
            orderPageQueryResponse.setCustomerName(obtcSaleOrderIndex.getMainCustomerName());
            orderPageQueryResponse.setSalesOrganization(obtcSaleOrderIndex.getMainOrganizationName());
            orderPageQueryResponse.setBuzChannel(obtcSaleOrderIndex.getMainChannelName());
            orderPageQueryResponse.setGoodsGroup(obtcSaleOrderIndex.getMainProductGroupName());
            orderPageQueryResponse.setSaleChannel(obtcSaleOrderIndex.getMainSaleChannelName());
            orderPageQueryResponse.setSaleDepartment(obtcSaleOrderIndex.getMainDepartmentName());
            orderPageQueryResponse.setCreator(obtcSaleOrderIndex.getMainCreatorName());
            orderPageQueryResponse.setRemark(obtcSaleOrderIndex.getMainRemark());
            orderPageQueryResponse.setReceiveAddressCode(obtcSaleOrderIndex.getMainReceiveAddressCode());
            orderPageQueryResponse.setReceiveDetailAddressName(obtcSaleOrderIndex.getMainReceiveDetailAddress());
            orderPageQueryResponse.setWareHouseCode(obtcSaleOrderIndex.getMainWareHouseCode());
            orderPageQueryResponse.setFrontOrderId(obtcSaleOrderIndex.getMainFrontOrderId());
            orderPageQueryResponse.setCustomerRefNo(obtcSaleOrderIndex.getMainCustomerReferenceNo());

            if (obtcSaleOrderIndex.getMainStatus() != null) {
                orderPageQueryResponse.setStatusCode(String.valueOf(obtcSaleOrderIndex.getMainStatus()));
                String desc = OrderStatus.of(Integer.parseInt(String.valueOf(obtcSaleOrderIndex.getMainStatus()))).getDesc();
                orderPageQueryResponse.setStatus(desc);
            }
            if (null != obtcSaleOrderIndex.getMainGmtCreate()) {
                SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
                String format = spf.format(obtcSaleOrderIndex.getMainGmtCreate());
                orderPageQueryResponse.setOrderTime(format);
            }
            if (SetOrderTag.RETURN.equals(request.getOrderTag())){
                orderPageQueryResponse.setOrderTotalFee(0L);
                if (finalSaleOrderTotalFeeMap.containsKey(Long.parseLong(orderPageQueryResponse.getId()))){
                    orderPageQueryResponse.setOrderTotalFee(finalSaleOrderTotalFeeMap.get(Long.parseLong(orderPageQueryResponse.getId())));
                }
            }

            //处理换货订单的交货单号
            if (EXCHANGE_ORDER_TAG.equals(request.getOrderTag()) && StringUtils.isNotBlank(orderPageQueryResponse.getDeliveryOrderId())){
                String[] deliveryOrderIds = orderPageQueryResponse.getDeliveryOrderId().split(",");
                if(deliveryOrderIds != null && deliveryOrderIds.length > 0){
                    for (String deliveryOrderId : deliveryOrderIds) {
                        Boolean flag = deliveryOrderMap.get(deliveryOrderId);
                        if (Boolean.TRUE.equals(flag)){
                            orderPageQueryResponse.setExchangeDeliveryOrderId(deliveryOrderId);
                        }else if (Boolean.FALSE.equals(flag)){
                            orderPageQueryResponse.setReturnDeliveryOrderId(deliveryOrderId);
                        }
                    }
                }
            }

            return orderPageQueryResponse;
        }).collect(Collectors.toList());
        return Result.listSuccess(orderPageQueryResponses, listResult.getTotal());

    }

    private Map<Long,Long> getSaleOrderTotalFee(List<Long> mainIdList) {
        HashMap<Long, Long> mainIdTotalFeeMap = new HashMap<>();
        List<OrderLine> orderLineList = new ArrayList<>();
        if (CollectionUtils.isEmpty(mainIdList)) {
            return mainIdTotalFeeMap;
        }
        QueryOrderLineByMainIdListRequest request = new QueryOrderLineByMainIdListRequest();
        request.setMainIdList(mainIdList);
        request.setStart(0);
        request.setLimit(1000);
        Result<List<OrderLine>> listResult = orderLineService.queryOrderLineByMainIdList(request);
        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
            orderLineList.addAll(listResult.getResult());
        }
        int total = listResult.getTotal();
        int totalPage = PageUtils.getTotalPage(total, 1000);
        if (totalPage > 1) {
            for (int i = 1; i < totalPage; i++) {
                request.setStart(i * 1000);
                request.setLimit(1000);
                Result<List<OrderLine>> pageResult = orderLineService.queryOrderLineByMainIdList(request);
                if (Objects.nonNull(pageResult) && CollectionUtils.isNotEmpty(pageResult.getResult())) {
                    orderLineList.addAll(pageResult.getResult());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(orderLineList)) {
            Map<Long, List<OrderLine>> mainIdGroupByMap = orderLineList.stream().collect(Collectors.groupingBy(OrderLine::getMainId));
            for (Map.Entry<Long, List<OrderLine>> mainEntry : mainIdGroupByMap.entrySet()) {
                List<OrderLine> orderLines = mainEntry.getValue();
                AtomicLong orderTotalFee = new AtomicLong(0L);
                if (CollectionUtils.isNotEmpty(orderLines)) {

                    orderLines.forEach(orderLine -> {
                        if (StringUtils.isNotBlank(orderLine.getFeatures())) {
                            HashMap<String, String> features = JSONObject.parseObject(orderLine.getFeatures(), HashMap.class);

                            if (!MapUtils.isEmpty(features)) {
                                //手工总金额
                                String manualTotalAmount = StringUtils.isNotBlank(features.get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT)) ? features.get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT) : null;
                                if (StringUtils.isNotBlank(manualTotalAmount)) {
                                    orderTotalFee.addAndGet(Long.parseLong(manualTotalAmount));
                                }
                            }
                        }
                    });
                }
                mainIdTotalFeeMap.put(mainEntry.getKey(), orderTotalFee.longValue());
            }
        }
        return mainIdTotalFeeMap;
    }

    /**
     * 处理换货交货单map 获取 交货单号 - true换货 false退货的
     * @param deliveryOrderMap
     * @param listResult
     */
    void handleExchangeDeliveryOrder(Map<String,Boolean> deliveryOrderMap,
                                     Result<List<ObtcSaleOrderIndex>> listResult ){
        try{
            //2022.10.20 获取到换货订单的交货单号合集 再去获取
            List<String> mainFeaturesDeliveryOrderId = Lists.newArrayList();
            listResult.getResult().stream().forEach(obtcSaleOrderIndex -> {
                if (StringUtils.isNotBlank(obtcSaleOrderIndex.getMainFeatures())){
                    Map<String,String> features = JSON.parseObject(obtcSaleOrderIndex.getMainFeatures(), Map.class);
                    if (StringUtils.isNotBlank(features.get(SaleOrderConstants.DELIVERY_ORDER_ID))){
                        mainFeaturesDeliveryOrderId.add(features.get(SaleOrderConstants.DELIVERY_ORDER_ID));
                    }
                }
            });
            String mainDeliveryOrderId = mainFeaturesDeliveryOrderId.stream()
//                    listResult.getResult().stream()
//                    .map(ObtcSaleOrderIndex::getMainDeliveryOrderId)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.joining(","));
            if (StringUtils.isBlank(mainDeliveryOrderId)){
                return;
            }
            List<String> mainDeliveryOrderIdList = Stream.of(mainDeliveryOrderId.split(",")).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(mainDeliveryOrderIdList)){
                return;
            }
            ConsignmentOrderLoadListRequest consignmentOrderLoadListRequest = new ConsignmentOrderLoadListRequest();
            consignmentOrderLoadListRequest.setOutDeliverOrderIdList(mainDeliveryOrderIdList);
            consignmentOrderLoadListRequest.setStatus(1);
            consignmentOrderLoadListRequest.setLimit(1000);
            Result<List<ConsignmentOrder>> result = consignmentOrderService.queryByOutDeliveryOrderIds(consignmentOrderLoadListRequest);
            if (result == null || CollectionUtils.isEmpty(result.getResult())){
                return;
            }
            List<Long> ids = result.getResult().stream().map(ConsignmentOrder::getId).collect(Collectors.toList());
            Map<String, Long> idMap = result.getResult().stream().collect(Collectors.toMap(ConsignmentOrder::getOuterDeliveryOrderId, ConsignmentOrder::getId,
                    (a, b) -> a));
            BatchQueryRequest batchQueryRequest = new BatchQueryRequest();
            // 因为consignOrderId索引是字符串 所以换成 String
            batchQueryRequest.setConsignmentOrderIds(ids.stream().map(String::valueOf).collect(Collectors.toList()));
            batchQueryRequest.setLimit(1000);
            Result<List<ConsignmentOrderLine>> lineResult = consignmentOrderLineService.batchQuery(batchQueryRequest);
            if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
                return;
            }
            Map<String, List<ConsignmentOrderLine>> subIdMap = lineResult.getResult().stream().collect(Collectors.groupingBy(ConsignmentOrderLine::getConsignmentOrderId));
            //目标获取到 交货单号 -- 换货/退货
            for (String code : mainDeliveryOrderIdList) {
                if (!idMap.containsKey(code)){
                    continue;
                }
                String deliveryOrderId = String.valueOf(idMap.get(code));
                if (!subIdMap.containsKey(deliveryOrderId)){
                    continue;
                }
                List<ConsignmentOrderLine> consignmentOrderLines = subIdMap.get(deliveryOrderId);
                if (CollectionUtils.isEmpty(consignmentOrderLines)){
                    continue;
                }
                boolean match = consignmentOrderLines.stream().anyMatch(x -> StringUtils.isNotBlank(x.getSoLineId()) && Integer.valueOf(x.getSoLineId().trim()) % 2 == 0);
                deliveryOrderMap.put(code,match);
            }
            log.info("query_sale_order_list_DeliveryOrderMap:{}", JSON.toJSONString(deliveryOrderMap));

        }catch (Throwable e){
            log.error("query_sale_order_list_consignmentOrderError",e);
        }
    }

}
